package com.bd.scm.module.utils;

import com.alibaba.fastjson.JSONObject;
import org.jboss.logging.Logger;

import java.util.Hashtable;
import java.util.Properties;

import javax.naming.*;
import javax.naming.directory.SearchControls;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.naming.directory.SearchResult;

/**
* Java通过Ldap操作AD的增删该查询
* @author guob
*/
public class LdapUtils {
	public static Logger logger = Logger.getLogger(LdapUtils.class);
	/**
	 * 获取ldap配置信息
	 */
	public static Properties properties = FilePathUtil.getProperties();

	static final Control[] connCtls = null;

	/**
	 *
	 * @param username LDAP 邮箱
	 * @param password LDAP 密码
	 * @return
	 */
	public static JSONObject checkLdap(String username, String password){//用户输入的邮箱,比如 afuz1 用户输入的密码，比如 12345678
		LdapContext ctx = null;
		//LDAP 登录名
		String userDN = "";
		JSONObject object = new JSONObject();
		object.put("code","00000");
		object.put("message","成功");
		try  {
			Hashtable env = new Hashtable();
			env.put(Context.SECURITY_AUTHENTICATION, properties.getProperty("security_authentication"));
			env.put(Context.SECURITY_PRINCIPAL, properties.getProperty("fixation_account")); //不要修改此值
			env.put(Context.SECURITY_CREDENTIALS, properties.getProperty("fixation_password")); //不要修改此值
			env.put(Context.INITIAL_CONTEXT_FACTORY,properties.getProperty("initial_context_factory"));
			env.put(Context.PROVIDER_URL, properties.getProperty("provider_url"));
//			env.put(Context.SECURITY_PROTOCOL, properties.getProperty("security_protocol"));
			ctx = new InitialLdapContext(env, connCtls);

			if(ctx==null) {
				logger.info("LDAP服务器连接失败");
				//LDAP服务器连接失败
				object.put("code","10002");
				object.put("message","LDAP服务器连接失败");
				return object;
			}

			SearchControls searchCtls = new SearchControls();
			searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

			NamingEnumeration<SearchResult> en = ctx.search("", "(mail="+username+")",searchCtls);

			if (en == null || !en.hasMoreElements()) {
				logger.info("LDAP中未找到该用户");
				//LDAP中未找到该用户
				object.put("code","10003");
				object.put("message","LDAP中未找到该用户");
				return object;
			}
			// maybe more than one element
			while (en != null && en.hasMoreElements()) {
				Object obj = en.nextElement();
				if (obj instanceof SearchResult) {
					SearchResult si = (SearchResult) obj;
					userDN += si.getName();
					userDN += ",ou=people,dc=example,dc=org";
				} else {
					logger.info("获取登录名:"+obj.toString());
				}
			}

			ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
			ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
			ctx.reconnect(connCtls);
			logger.info("验证通过:"+userDN);
			ctx.close();
		} catch (AuthenticationException e) {
			logger.info("验证失败:"+userDN);
			logger.info("LDAP验证错误:"+e.toString());
			//LDAP登录名密码验证错误
			object.put("code","10004");
			object.put("message","LDAP登录名密码验证错误");
			return object;
		} catch (NamingException e) {
			logger.info("验证失败:"+userDN);
			logger.info("LDAP验证错误:"+e.toString());
			//LDAP登录名密码验证错误
			object.put("code","10005");
			object.put("message","LDAP验证错误");
			return object;
		}
		return object;
	}












public static void main(String[] args) {
		Properties properties = FilePathUtil.getProperties();
		System.out.println("证书路径:"+properties.getProperty("trustStore"));
		System.out.println("证书密码:"+properties.getProperty("keyStorePassword"));
		System.out.println("安全证明:"+properties.getProperty("security_authentication"));
		System.out.println("域名:"+properties.getProperty("security_principal"));
		System.out.println("初始上下文工厂:"+properties.getProperty("initial_context_factory"));
		System.out.println("提供者URL:"+properties.getProperty("provider_url"));
		System.out.println("安全协议:"+properties.getProperty("security_protocol"));
	}
}
